package com.digitalchina.lxnsy.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.EvaluateOrderActivity;
import com.digitalchina.lxnsy.activity.old.LogisticsQueryActivity;
import com.digitalchina.lxnsy.activity.old.OrderDetailsActivity;
import com.digitalchina.lxnsy.api.BusinessFarmSystem;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.MyOrderListVO;
import com.digitalchina.lxnsy.interfaces.IOrderCallBack;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.OrderItemHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

import static android.app.Activity.RESULT_OK;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2017/8/7 19:30
 * 修改备注：
 * ================================================
 */
public class OrderFragment extends BaseV4Fragment implements SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener, IOrderCallBack {

    private RecyclerArrayAdapter adapter;
    private List<MyOrderListVO> voList = new ArrayList<>();

    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;

    private String queryStatus = "";
    private int page = 1;
    private String limit = "10";

    @Override
    public void initMember() {
        if (getArguments() != null) {
            queryStatus = getArguments().getString("queryStatus");
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(getActivity()) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new OrderItemHolder(parent, OrderFragment.this);
            }
        });

        onRefresh();
    }

    @Override
    public void addListener() {

        recyclerView.setRefreshListener(this);

        recyclerView.addItemDecoration(Utils.setDividerDecoration(getActivity(), 1.0f, 10.0f, 10.0f));

        adapter.setNoMore(R.layout.view_nomore);
        adapter.setMore(R.layout.view_more, this);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getActivity(), OrderDetailsActivity.class);
                intent.putExtra("MyOrderListVO", (Serializable) adapter.getItem(position));
                startActivityForResult(intent, 99);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99 && resultCode == RESULT_OK) {
            onRefresh();
        }
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (getActivity()==null||getActivity().isFinishing())
                    return;
                recyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_GET_BUYER_ORDER_BY_STATUS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_BUYER_ORDER_BY_STATUS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_CANCEL_ORDER_AGSRV_SUCCESS:
                        showToast("订单已取消");
                        onRefresh();
                        break;
                    case MSG.MSG_CANCEL_ORDER_AGSRV_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_DELETE_ORDER_AGSRV_SUCCESS:
                        showToast("订单已删除");
                        onRefresh();
                        break;
                    case MSG.MSG_DELETE_ORDER_AGSRV_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_AFFIRM_RECEIPT_SUCCESS:
                        showToast("已确认收货");
                        onRefresh();
                        break;
                    case MSG.MSG_AFFIRM_RECEIPT_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "orderList", MyOrderListVO.class);

        if (voList == null)
            return;

        if (page == 1)
            adapter.clear();

        adapter.addAll(voList);

        if (voList.size() < Integer.parseInt(limit)) {
            adapter.stopMore();
        }
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_order);
    }

    @Override
    public void onRefresh() {
        page = 1;
        if (StringUtil.isStrEmpty(queryStatus))
            BusinessFarmSystem.getOrderListAll(getActivity(), String.valueOf(page), limit, mHandler);
        else
            BusinessFarmSystem.getBuyerOrderByStatus(getActivity(), queryStatus, String.valueOf(page), limit, mHandler);
    }

    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= Integer.parseInt(limit)) {
            page++;
            if (StringUtil.isStrEmpty(queryStatus))
                BusinessFarmSystem.getOrderListAll(getActivity(), String.valueOf(page), limit, mHandler);
            else
                BusinessFarmSystem.getBuyerOrderByStatus(getActivity(), queryStatus, String.valueOf(page), limit, mHandler);
        }
    }

    @Override
    public void onDeleteClick(int pos) {
        MyOrderListVO vo = (MyOrderListVO) adapter.getAllData().get(pos);
        BusinessFarmSystem.deleteOrder(getActivity(), vo.getOrderNo(), mHandler);
    }

    @Override
    public void onCancelClick(int pos, String reason) {
        MyOrderListVO vo = (MyOrderListVO) adapter.getAllData().get(pos);
        BusinessFarmSystem.cancelOrder(getActivity(), vo.getOrderNo(), reason, mHandler);
    }


    @Override
    public void onAffirmClick(int pos) {
        MyOrderListVO vo = (MyOrderListVO) adapter.getAllData().get(pos);
        BusinessFarmSystem.affirmReceipt(getActivity(), vo.getOrderNo(), mHandler);
    }

    @Override
    public void onPayClick(int pos) {

    }

    @Override
    public void onEvaluateClick(int pos) {
        Intent intent = new Intent(getActivity(), EvaluateOrderActivity.class);
        intent.putExtra("myOrderListVO", (Serializable) adapter.getItem(pos));
        startActivityForResult(intent, 99);
    }

    @Override
    public void onLogisticsClick(int pos) {
        MyOrderListVO vo = (MyOrderListVO) adapter.getAllData().get(pos);
        GotoUtil.gotoActivity(getActivity(), LogisticsQueryActivity.class, "orderNo", vo.getOrderNo());
    }

    @Override
    public void onDetailClick(int pos) {

    }

    @Override
    public void onVerificationClick(int pos, String verificationCode) {

    }
}
